const router = require('koa-router')();
const mysqlHelper = require('../libs/MySQLHelper');
const scripts = require('../configs/scripts/msyql');

router.prefix('/api/alliance');

/**
 * 获取仓盟参数列表。
 */
router.get('/list', async (ctx, next) => {
    await mysqlHelper.queryForList(scripts.GetAllianceParameters, ctx.query, sb => sb.and('Name=@name')).then(res => ctx.body = res, reason => ctx.body = reason);
});

/**
 * 保存仓盟设置参数。
 */
router.post('/save', async (ctx, next) => {
    const data = ctx.request.body;
    const user = ctx.session.user;

    data.CreateUserID = user.StaffID;
    data.CreateUserName = user.Name;
    data.UpdateUserID = user.StaffID;
    data.UpdateUserName = user.Name;

    let paramter = {};

    await mysqlHelper.query(scripts.CheckAllianceParameterExist, data).then(res => paramter = res.datas[0]);

    if (paramter && paramter.Name) {
        await mysqlHelper.query(scripts.UpdateAllianceParameter, data).then(res => ctx.body = res, reason => ctx.body = reason);
    } else {
        data.GUID = mysqlHelper.generateUUID();

        await mysqlHelper.query(scripts.AddAllianceParameter, data).then(res => ctx.body = res, reason => ctx.body = reason);
    }
});

module.exports = app => {
    app.use(router.routes(), router.allowedMethods());
};